#!/bin/bash
TTY=$1
echo ${TTY}
ntty=$(echo $TTY|sed -e 's/tty//g')
#id=$(date +%N|cut -b 3-6)
id="NOFIX"
cpuserial=$(printf "%d\n" 0x$(cat /proc/cpuinfo |grep Serial|cut -d: -f2|sed -e 's/^ //'))
ttymajor=$(udevadm info --name=/dev/ttyUSB1|sed -n '/MAJOR/{s/[A-Z: =]*//;p}')
ttyminor=$(udevadm info --name=/dev/ttyUSB1|sed -n '/MINOR/{s/[A-Z: =]*//;p}')

grep G /dev/${TTY}|while read line
do
  case $line in
    *TXT*,*unknown*,*VTG*,*PUBX*)
    ;;
    *RMC*)
		if [ "$line" == "*,,,,*" ]; then
		  id="NOFIX"
		else
		  id=$(echo $(date +%s)$(echo $(date +%N|cut -b -3))${ttymajor}${ttyminor})
		echo $id
		  echo "insert into gps.gpsin (cpuserial,interface,epoch,fixid,payload) values ($cpuserial,'$ntty',$(date +%s)$(date +%N|cut -b -3),$id,'$line');"|mysql -h pisql -u gps -pgps
#		  echo "insert into gps.gpsin (cpuserial,interface,epoch,fixid,payload) values ($cpuserial,'$ntty',$(date +%s)$(date +%N|cut -b -3),$id,'$line');"
#		  echo ${ntty},$(date +%s).$(date +%N|cut -b -3),$id,$line |sed -e 's/,[NWESAV]/,/g;s/\.[0]*,/,/g;s/*.*//g;s/,0*/,/g;s/[,]*$//g' >> /tmp/gps_$(date +%j%H%M)
		fi
    ;;
    *GSV*)
		if [ "$id" != "NOFIX" ]; then
		  echo "insert into gps.gpsin (cpuserial,interface,epoch,fixid,payload) values ($cpuserial,'$ntty',$(date +%s)$(date +%N|cut -b -3),$id,'$line');"|mysql -h pisql -u gps -pgps
#			echo ${ntty},$(date +%s).$(date +%N|cut -b -3),$id,$line |sed -e 's/*.*//g;s/,0*/,/g' >> /tmp/gps_$(date +%j%H%M)
		fi
	;;
    *GSA*)
		if [ "$id" != "NOFIX" ]; then
		  echo "insert into gps.gpsin (cpuserial,interface,epoch,fixid,payload) values ($cpuserial,'$ntty',$(date +%s)$(date +%N|cut -b -3),$id,'$line');"|mysql -h pisql -u gps -pgps
		fi
	;;
    *GGA*)
		if [ "$id" != "NOFIX" ]; then
		  echo "insert into gps.gpsin (cpuserial,interface,epoch,fixid,payload) values ($cpuserial,'$ntty',$(date +%s)$(date +%N|cut -b -3),$id,'$line');"|mysql -h pisql -u gps -pgps
		#	echo ${ntty},$(date +%s).$(date +%N|cut -b -3),$id,$line |sed -e 's/,[MNESW]/,/g;s/*.*//g;s/,0*/,/g;s/\.[0]*,/,/g' >> /tmp/gps_$(date +%j%H%M)
		fi
	;;
    *GBS*)
		if [ "$id" != "NOFIX" ]; then
		  echo "insert into gps.gpsin (cpuserial,interface,epoch,fixid,payload) values ($cpuserial,'$ntty',$(date +%s)$(date +%N|cut -b -3),$id,'$line');"|mysql -h pisql -u gps -pgps
		#	echo ${ntty},$(date +%s).$(date +%N|cut -b -3),$id,$line |sed -e 's/*.*//g;s/,0*/,/g' >> /tmp/gps_$(date +%j%H%M)
		fi
	;;
    *GST*)
		if [ "$id" != "NOFIX" ]; then
		  echo "insert into gps.gpsin (cpuserial,interface,epoch,fixid,payload) values ($cpuserial,'$ntty',$(date +%s)$(date +%N|cut -b -3),$id,'$line');"|mysql -h pisql -u gps -pgps
		#	echo ${ntty},$(date +%s).$(date +%N|cut -b -3),$id,$line |sed -e 's/*.*//g;s/,0*/,/g' >> /tmp/gps_$(date +%j%H%M)
		fi
	;;
  esac
done

